package com.dongdongshop.service.impl;

import com.dongdongshop.pojo.TbGoods;
import com.dongdongshop.pojo.TbGoodsDesc;
import com.dongdongshop.pojo.TbItem;
import com.dongdongshop.service.TbgoodService;
import com.dongdongshop.service.itemPageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class itemPageServiceimpl implements itemPageService {

    @Autowired
    private FreeMarkerConfigurer fmc;

    @DubboReference
    private TbgoodService ts;//调用good表查询数据



    //生成html页面
    @Override
    public void create(Long id) {
        //1。创建一个Configuration对象
        Configuration configuration=fmc.getConfiguration();
        //2.加载一个模板，创建一个模板对象
        FileWriter fileWriter=null;
        try {
            Template template = configuration.getTemplate("item.ftl");

            //根据id查询数据，放入map
            TbGoods goods = ts.bygoods(id);
            TbGoodsDesc goodesc = ts.bygoodsdescid(id);
            List<TbItem> tbls = ts.byitemgoodid(id);

            //5.创建一个模板使用的数据集，可以是pojo,map,
            Map<String,Object> map=new HashMap<>();
            map.put("goods",goods);
            map.put("goodesc",goodesc);
            map.put("itemlist",tbls);


            //6.创建一个writer对象，一般创建FileWriter对象，指定生成的文件名
            fileWriter=new FileWriter("D:\\e\\freemarker\\"+id+".html");

            //7.调用模板对象的process方法输出文件
            template.process(map,fileWriter);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //8.关流
            if(fileWriter!=null){
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
